/*
 * Copyright (C) 2009 Georgios J. Georgopoulos, All rights reserved.
 * 
 * This is free software; you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 3 of the License, or (at your option) any
 * later version.
 * 
 * This software is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this software; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
 * site: http://www.fsf.org.
 */
package org.gwt.mosaic.xul.client.application;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;

import org.gwt.mosaic.xul.client.ui.Element;

/**
 * 
 * @author georgopoulos.georgios(at)gmail.com
 * 
 */
public class ElementMap {

  private ElementMap parent;
  
  private HashMap<Object, Element> table;
  
  public ElementMap() {
    // Nothing to do here!
  }
  
  public Object[] allKeys() {
    Object[] keys = keys();
    if (parent == null) {
      return keys;
    }
    Object[] parentKeys = parent.allKeys();
    if (keys.length == 0) {
      return parentKeys;
    }
    if (parentKeys.length == 0) {
      return keys;
    }
    HashSet<Object> keySet = new HashSet<Object>(Arrays.asList(keys));
    keySet.addAll(Arrays.asList(parentKeys));
    return keySet.toArray(new Object[keySet.size()]);
  }

  public void clear() {
    if (table != null) {
      table.clear();
    }
  }

  public Element get(Object key) {
    Element element = null;
    if (table != null) {
      element = table.get(key);
    }
    if (element == null && getParent() != null) {
      element = getParent().get(key);
    }
    return element;
  }

  public ElementMap getParent() {
    return parent;
  }

  public Object[] keys() {
    if (table == null) {
      return new Object[0];
    }
    return table.keySet().toArray(new Object[table.size()]);
  }

  public void put(Object key, Element action) {
    if (action != null) {
      if (table == null) {
        table = new HashMap<Object, Element>();
      }
      table.put(key, action);
    } else {
      remove(key);
    }
  }

  public void remove(Object key) {
    if (table != null) {
      table.remove(key);
    }
  }

  public void setParent(final ElementMap parent) {
    this.parent = parent;
  }

  public int size() {
    return (table != null) ? table.size() : 0;
  }
}
